<template>
  <!--图片放大区域-->
  <div class="preview">
    <div class="pic" @mousemove="handler">
      <img :src="imgObj.imgUrl" alt="图片加载失败" />
      <div class="big">
        <img :src="imgObj.imgUrl" alt="图片加载失败" ref="bigImage" />
      </div>
      <div class="mask" ref="mask"></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentIndex: 0,
    };
  },
  name: "Zoom",
  props: ["skuImageList"],
  computed: {
    imgObj() {
      return this.skuImageList[this.currentIndex] || {};
    },
  },
  methods: {
    handler(event) {
      let mask = this.$refs.mask;
      let bigImage = this.$refs.bigImage;
      let left = event.offsetX - mask.offsetWidth / 2;
      let top = event.offsetY - mask.offsetHeight / 2;
      if (left <= 0) left = 0;
      if (left >= mask.offsetWidth) left = mask.offsetWidth;
      if (top <= 0) top = 0;
      if (top >= mask.offsetHeight) top = mask.offsetHeight;
      mask.style.left = left + "px";
      mask.style.top = top + "px";
      bigImage.style.left = -2 * left + "px";
      bigImage.style.top = -2 * top + "px";
    },
  },
  mounted() {
    //全局事件总线，获取兄弟组件轮播图给的index
    this.$bus.$on("getIndex", (index) => {
      this.currentIndex = index;
    });
  },
};
</script>

<style lang="css" scoped>
.preview {
  float: left;
  width: 400px;
  margin-bottom: 10px;
}
.preview .pic {
  cursor: pointer;
  width: 400px;
  height: 400px;
  border: 1px solid #dfdfdf;
  position: relative;
}
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.big {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 420px;
  top: 0;
  z-index: 999;
  border: 1px solid #dfdfdf;
  overflow: hidden;
  display: none;
}
.big img {
  width: 200%;
  max-width: 200%;
  height: 200%;
  position: absolute;
  left: 0;
  top: 0;
}
.mask {
  width: 50%;
  height: 50%;
  background-color: rgba(255, 255, 255, 0.3);
  border: 1px solid #dfdfdf;
  position: absolute;
  z-index: 2;
  display: none;
  pointer-events: none;
}
.pic:hover .mask,
.pic:hover .big {
  display: block;
}
</style>
